package com.kgc.sso.service.impl;

import com.kgc.dao.TbUserMapper;
import com.kgc.entity.TbUser;
import com.kgc.entity.TbUserExample;
import com.kgc.jedis.JedisClient;
import com.kgc.sso.service.UserService;
import com.kgc.utils.ItripResult;

import com.kgc.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;


import javax.jms.*;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private TbUserMapper tbUserMapper;
    @Autowired
    private JedisClient jedisClient;

    @Autowired
    private JmsTemplate jmsTemplate;
    @Autowired
    private Destination destination;
    @Value("${USERTOKENID}")
    private String USERTOKENID;

    @Value("${TOKENIDTIMEOUT}")
    private int TOKENIDTIMEOUT;
    @Override
    public ItripResult checkData(String param, Integer type) {
        TbUserExample example =new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        List<TbUser> list=null;
        if (type==1){
            criteria.andUsernameEqualTo(param);
            list= tbUserMapper.selectByExample(example);
            if(list!=null&&list.size()>0){//当前这个用户名已存在
                return ItripResult.build(400,"用户名已存在");
            }else{
                return ItripResult.build(200,"ok",true);

            }
        }else if (type==2){
            criteria.andPhoneEqualTo(param);
            list= tbUserMapper.selectByExample(example);
            if(list!=null&&list.size()>0){//当前这个用户名已存在
                return ItripResult.build(400,"电话已存在");
            }else{
                return ItripResult.build(200,"ok",true);
            }
        }else if (type==3){
            criteria.andEmailEqualTo(param);
            list= tbUserMapper.selectByExample(example);
            if(list!=null&&list.size()>0){//当前这个用户名已存在
                return ItripResult.build(400,"邮箱已注册");
            }else{
                return ItripResult.build(200,"ok",true);
            }
        }
        return ItripResult.build(400,"检查的数据无效");
    }

    @Override
    public ItripResult register(TbUser user) {
        if(StringUtils.isEmpty(user.getUsername())){
            return ItripResult.build(400,"用户名不能为空!");
        }else{
            ItripResult result=  checkData(user.getUsername(),1);
            if(result.getStatus()==400) return result;
        }
        if(StringUtils.isEmpty(user.getPhone())){
            return ItripResult.build(400,"电话不能为空!");
        }else{
            ItripResult result=  checkData(user.getPhone(),2);
            if(result.getStatus()==400) return result;
        }
        if(StringUtils.isEmpty(user.getEmail())){
            return ItripResult.build(400,"email不能为空!");
        }else{
            ItripResult result=  checkData(user.getEmail(),3);
            if(result.getStatus()==400) return result;
        }
        //表示用户的信息都 是合法可以注册
        final String  code= UUID.randomUUID().toString();
        user.setCode(code);
        user.setState(0);//未激活
        jmsTemplate.send(destination, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage textMessage=session.createTextMessage(code);
                return textMessage;
            }
        });

        user.setUpdated(new Date());
        user.setCreated(new Date());
        String pwd= DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(pwd);
        tbUserMapper.insertSelective(user);
        return ItripResult.build(200,"ok",true);
    }

    @Override
    public ItripResult userLogin(String username, String password) {
        TbUserExample example=new TbUserExample();
        List<TbUser> list=null;
        TbUserExample.Criteria criteria = example.createCriteria();
        //按用户名查询
        criteria.andUsernameEqualTo(username);
        list=tbUserMapper.selectByExample(example);
        TbUser user=null;

        if(list==null||list.size()==0){
            return ItripResult.build(400,"用户名不存在!");
        }else{
           user=list.get(0);
            if(user.getState()==0){
                return ItripResult.build(400,"用户名请先激活再使用!");
            }
            String pwd=user.getPassword();//数据库加密过的密码
            if (!pwd.equals(DigestUtils.md5DigestAsHex(password.getBytes()))){
                return ItripResult.build(400, "用户名密码错误!");
            }
            //用户名与密码是正确的
            //将登录成功的用户信息存储到redis中  30分钟  key-value
            String token=UUID.randomUUID().toString();//key
            String jsonString= JsonUtils.objectToJson(user);//value
            //写入redis 设有效期
            jedisClient.set(USERTOKENID+token,jsonString);
            jedisClient.expire(USERTOKENID+token,TOKENIDTIMEOUT);
            return ItripResult.build(200,"ok",token);
        }

    }

    @Override
    public ItripResult getUserByToken(String token) {
        String jsonString=null;
        if(jedisClient.exists(USERTOKENID+token)){
            jsonString=jedisClient.get(USERTOKENID+token);
        }
        if(StringUtils.isEmpty(jsonString)){
            return ItripResult.build(400,"当前用户过期!");
        }
        jedisClient.expire(USERTOKENID+token,TOKENIDTIMEOUT);
        TbUser user=JsonUtils.jsonToPojo(jsonString,TbUser.class);
        System.out.println(user);
        return ItripResult.build(200,"ok",user);
    }

    @Override
    public TbUser getUserByCode(String code) {
        TbUserExample example=new TbUserExample();
        List<TbUser> list=null;
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andCodeEqualTo(code);
        list=tbUserMapper.selectByExample(example);
        TbUser user=list.get(0);
        return user;
    }
    @Override
    public ItripResult jihuo(String code){
        TbUser user= getUserByCode(code);
        user.setState(1);//将0 修改为1
        tbUserMapper.updateByPrimaryKey(user);
        return ItripResult.ok();
    }
}
